<template>
  <div class="app-container">

    <div class="" style="background: #ffffff; padding: 20px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="捐赠来源" prop="sourceId">
          <el-select v-model="queryParams.sourceId" filterable placeholder="请选择捐赠来源" style="">
            <el-option
              v-for="item in donate_option"
              :key="item.id"
              :label="item.donateName"
              :value="item.id"
              @keyup.enter.native="handleQuery"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['donate:donate:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['donate:donate:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['donate:donate:remove']"
          >删除
          </el-button>
        </el-col>
        <!--      <el-col :span="1.5">-->
        <!--        <el-button-->
        <!--          type="warning"-->
        <!--          plain-->
        <!--          icon="el-icon-download"-->
        <!--          size="mini"-->
        <!--          @click="handleExport"-->
        <!--          v-hasPermi="['donate:donate:export']"-->
        <!--        >导出-->
        <!--        </el-button>-->
        <!--      </el-col>-->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>

    <div class="" style="background: #ffffff; padding: 20px; margin: 20px 0 0">
      <el-table v-loading="loading" :data="donateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column label="捐赠编号" align="center" prop="donationNumber"/>
        <el-table-column label="捐赠图片" align="center" prop="indexImg">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.indexImg"
              fit="fit"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="总价" align="center" prop="totalPrice"/>
        <el-table-column label="捐赠来源" align="center" prop="sourceName">
          <template slot-scope="scope">
            <div v-for="item in scope.row.sourceName">{{ item }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['donate:donate:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['donate:donate:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改捐赠列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="捐赠编号:" prop="donationNumber" v-if="form.id!=null">
          <div>{{ form.donationNumber }}</div>
        </el-form-item>
        <el-form-item label="捐赠图片" prop="indexImg">
          <el-upload
            class="avatar-uploader"
            action
            :http-request="selectPicUpload"
            :show-file-list="false"
          >
            <img v-if="form.indexImg" :src="form.indexImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="捐赠来源" prop="arDonateSources">
          <el-select
            v-model="form.arDonateSources"
            multiple
            filterable
            allow-create
            default-first-option
            value-key="id"
            placeholder="请选择捐赠来源"
          >
            <el-option
              v-for="item in donate_option"
              :key="item.id"
              :label="item.donateName"
              :value="{ id: item.id }"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <!--        商品选项-->
        <div class="text-bold" style="margin: 20px 0; font-size: medium">捐赠物品</div>

        <div v-if="open"
             :style="{'overflow-y': (form.arDonations.length > 3 ? 'auto' : ''), height: (form.arDonations.length > 3 ? '550px' : ''),padding: '0 20px 0 0'}"
        >

          <div v-for="(arDonations,index) in form.arDonations" :key="index">
            <div class="flex-row-bt" style="margin: 20px 0">
              <div class="text-bold" style=" color: #409EFF">物资{{ index + 1 }}</div>
              <!--          删除选项-->
              <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="deleteSelect(index)"
              ></el-button>
            </div>

            <div class="flex-row">
              <el-form-item label="物资名称" :prop="'arDonations.' + index + '.materialName'"
                            :rules="[{required: true, message: '请输入物资名称', trigger: 'change'}]"
                            style="width: 48%;margin-right: 30px;"
              >
                <el-input v-model="arDonations.materialName" placeholder="请输入物资名称"/>
              </el-form-item>
              <el-form-item label="物品类别" :prop="'arDonations.' + index + '.specifications'"
                            :rules="[{required: true, message: '请输入物品类别', trigger: 'change'}]"
              >
                <el-input v-model="arDonations.specifications" placeholder="请输入物品类别"/>
              </el-form-item>
            </div>
            <div class="flex-row">
              <el-form-item label="物品数量" :prop="'arDonations.' + index + '.itemNumber'"
                            :rules="[{required: true, message: '请输入物品数量', trigger: 'change'}]"
                            style="margin-right: 20px;"
              >
                <el-input-number v-model="arDonations.itemNumber" size="medium" :min="1" label="请输入物品数量"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="单价" :prop="'arDonations.' + index + '.monovalent'"
                            :rules="[{required: true, message: '请输入单价', trigger: 'change'}]"
                            style="margin-right: 20px;"
              >
                <el-input v-model="arDonations.monovalent" placeholder="请输入单价" type="number"/>
              </el-form-item>
              <!--              <el-form-item label="总价" :prop="'arDonations.' + index + '.totalPrice'"-->
              <!--                            :rules="[{required: true, message: '请输入总价', trigger: 'change'}]"-->
              <!--                            styles="width: 55%"-->
              <!--              >-->
              <!--                <el-input v-model="arDonations.totalPrice" placeholder="请输入总价"/>-->
              <!--              </el-form-item>-->
            </div>

          </div>

        </div>

        <el-button type="primary" size="small" plain @click="addSelect" style="margin-top: 10px">增加选项</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDonate, getDonate, delDonate, addDonate, updateDonate, delDonations, uploadPic } from '@/api/donate/donate'
import { imgUrl } from '@/utils/request'
import { donateList } from '@/api/donate/source'

export default {
  name: 'Donate',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 捐赠列表表格数据
      donateList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sourceId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        donateName: [
          { required: true, message: '请输入捐赠人', trigger: 'change' }
        ],
        indexImg: [
          { required: true, message: '请上传捐赠图片', trigger: 'change' }
        ],
        arDonateSources: [
          { type: 'array', required: true, message: '请选择捐赠来源', trigger: 'change' }
        ],
        arDonations: [
          { type: 'array', required: true, message: '请添加物资', trigger: 'change' }
        ]
      },
      //图片路径
      imgUrl,
      //捐赠来源list
      donate_option: []
    }
  },
  created() {
    this.getList()
    //获取捐赠来源list
    this.getDonateList()
  },
  methods: {
    //获取捐赠来源list
    getDonateList() {
      donateList().then(response => {
        this.donate_option = response
      })
    },
    //上传商品图片
    selectPicUpload(obj) {
      let fd = new FormData() //参数的格式是formData格式的
      fd.append('file', obj.file) //参数
      uploadPic(fd, { modularName: 'DONATION' }).then(res => {
        this.form.cover = res
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //增加商品选项
    addSelect() {
      this.form.arDonations.push({
        'itemNumber': null,
        'materialName': null,
        'monovalent': null,
        'specifications': null,
        'totalPrice': null
      })
    },
    //删除商品选项
    deleteSelect(index) {
      this.$modal.confirm('是否确认删除此物资选项?').then(function() {
      }).then(() => {
        if (this.form.arDonations[index].id) {
          delDonations(this.form.arDonations[index].id).then(response => {
            if (response.code === 200) {
              this.form.arDonations.splice(index, 1)
              this.$modal.msgSuccess('删除成功')
            } else {
              this.$modal.msgError(response.msg)
            }
          })
        } else {
          this.form.arDonations.splice(index, 1)
          this.$modal.msgSuccess('删除成功')
        }
      }).catch(() => {
      })

      // this.$modal.confirm('是否确认删除此捐赠物品?').then(function() {
      // }).then(() => {
      //   this.form.arDonations.splice(index, 1)
      //   this.$modal.msgSuccess('删除成功')
      // }).catch(() => {
      // })
    },
    /** 查询捐赠列表列表 */
    getList() {
      this.loading = true
      listDonate(this.queryParams).then(response => {
        this.donateList = response.pageData
        this.total =Number(response.total)
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        donationNumber: null,
        arDonateSources: [],
        indexImg: null,
        remark: null,
        arDonations: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加捐赠列表'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDonate(id).then(response => {
        this.form = response
        console.log(this.form)
        this.open = true
        this.title = '修改捐赠列表'
      })
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.arDonations.length == 0 || this.form.arDonations == null) {
        this.$modal.msgError('请添加捐赠物品')
      } else {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              console.log(this.form)
              updateDonate(this.form).then(response => {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
            } else {
              addDonate(this.form).then(response => {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
            }
          }
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除该捐赠信息？').then(function() {
        return delDonate(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('donate/donate/export', {
        ...this.queryParams
      }, `donate_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
